const api = require('../../api/api')
const util = require('../../utils/js/util')
const app = getApp()
Page({
  data: {
    userInfo: {},
    menusBottom: util.getMenuButton().bottom,
    bannerCurrent: 0, // banner当前索引
    bannerList: [],
    menusTwoList: [],
    tabactive: 0, // tab下标
    tablist: [], // tab列表
    doctorList: [], // 医生列表
    page: 1, // 页码
    listStatus: 'loading', // 列表状态
  },

  async onLoad(query) {
    console.log(query);
    // const scene = decodeURIcomponent(query.scene)
    // console.log(scene);
    await app.login()
    this.setData({ userInfo: app.globalData.userInfo })
    this.getbanner();
    await this.getHomeDiseaseList();
    this.getServiceList();
  },

  // 获取banner
  async getbanner() {
    const res = await api.getBannerList()
    this.setData({ bannerList: res })
  },

  // 触底刷新
  onReachBottom() {
    if (this.data.listStatus === 'loading') {
      this.setData({ page: this.data.page + 1 })
      this.getServiceList();
    }
  },

  // 跳转检查页面
  gotoCheck() {
    wx.switchTab({ url: '../check/index' })
  },

  // 跳转报告页面
  gotoReport() {
    wx.switchTab({ url: '../report/index' })
  },

  // 跳转体检
  gotoExam() {
    wx.navigateTo({ url: '../result/index?query=职业体检' })
  },

  // 获取菜单
  async getHomeDiseaseList() {
    const res = await api.getHomeDiseaseList()
    res.home_disease_level_2.push({
      name: '更多',
      icon: '../../static/img/index/more.png'
    })
    this.setData({
      menusTwoList: res.home_disease_level_2,
      tablist: res.home_disease_recommend
    })
  },

  // 获取服务列表  
  async getServiceList() {
    const res = await api.getServiceList({ query: this.data.tablist[this.data.tabactive].name, p: this.data.page })
    const newdata = (res?.data || []).map(v => ({
      ...v,
      tags: v.tags.split('/')
    }))
    this.setData({
      doctorList: this.data.page == 1 ? newdata : this.data.doctorList.concat(newdata),
      listStatus: res.current_page == res.last_page ? 'tobottom' : res.current_page < res.last_page ? 'loading' : res.current_page > res.last_page ? 'nodata' : ''
    })
  },

  // tab改变
  tabchange({ currentTarget: { dataset: { index } } }) {
    if (index != this.data.tabactive) {
      this.setData({ tabactive: index, page: 1 })
      this.getServiceList()
    }
  },

  // 去搜索病名
  gotosearch(e) {
    console.log(e);
    wx.navigateTo({ url: '../result/index?query=' + (e?.currentTarget?.dataset?.item?.name || e.detail.value) })
  },

  // banner改变
  bannerChange(e) {
    // console.log(e);
  },

  // 跳转医生详情
  gotoDoctorDetail({ currentTarget: { dataset: { id } } }) {
    wx.navigateTo({ url: '../doctor/index?id=' + id })
  }
})
